package leetcode;

public class LeetCode59 {

    //向右  column++
    //向下  row++
    //向左  column--
    //向上  row--
//    public int[][] generateMatrix(int n) {
//        int[][] result = new int[n][n];
//        int endPoint = n * n, row = 0, column = 0;
//        String directive = "right";
//        for (int i = 1; i <= endPoint; i++) {
//            result[row][column] = i;
//            if (directive.equals("right")) {
//                if (column == n - 1) {
//                    directive = "down";
//                    row--;
//                }else
//                    column++;
//            }
//        }
//    }
//------------------------------------------------------------------
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int i = 1;
        int X_Begin = 0;
        int X_End = n - 1;
        int Y_Begin = 0;
        int Y_End = n - 1;
        while (i <= n * n) {
            //水平向右
            for (int j = X_Begin; j <= X_End; j++) {
                res[Y_Begin][j] = i++;
            }
            Y_Begin++;

            //垂直向下
            for (int j = Y_Begin; j <= Y_End; j++) {
                res[j][X_End] = i++;
            }
            X_End--;

            //水平向左
            for (int j = X_End; j >= X_Begin; j--) {
                res[Y_End][j] = i++;
            }
            Y_End--;

            //水平向上
            for (int j = Y_End; j >= Y_Begin; j--) {
                res[j][X_Begin] = i++;
            }
            X_Begin++;
        }

        return res;
    }
}
